<template>
  <div class="loginmodal">
    <!-- 使用兄弟元素作为背景，避免事件冒泡 触发子元素的点击事件 -->
    <div class="mask"></div>
    <div class="loginBox">
      <img
        src="../assets/img/close.png"
        alt=""
        @click="changeIsShowLogin(false)"
        class="close"
      />
      <div class="switchOn">
        <div
          @click="isShowLoginType = true"
          :class="{ active: isShowLoginType }"
          class="phonelogin"
        >
          手机号登录
        </div>
        |
        <div
          :class="{ active: !isShowLoginType }"
          @click="showQrCode"
          class="qrlogin"
        >
          微信扫码登录
        </div>
      </div>
      <!-- 手机号登陆 -->
      <section v-show="isShowLoginType" class="phoneLogin">
        <div class="row">
          <input
            class="ipt"
            v-model="phoneNumber"
            placeholder="请输入手机号"
            type="text"
          />
        </div>
        <!-- <div class="row">
          <input class="ipt" placeholder="请输入密码" type="password" />
        </div> -->
        <slide-verify
          :l="42"
          :r="20"
          :w="362"
          :h="140"
          @success="onSuccess"
          @fail="onFail"
          @refresh="onRefresh"
          :style="{ width: '100%' }"
          class="slide-box"
          ref="slideBlock"
          :slider-text="msg"
        ></slide-verify>
        <div class="row">
          <input
            class="ipt"
            v-model="Code"
            placeholder="请输入验证码"
            type="text"
          />
          <button class="btn btncode" @click="getCode" v-show="getCodeStatus">
            获取验证码
          </button>
          <button class="btn btncode" v-show="!getCodeStatus">
            {{ `${count}s后从新获取` }}
          </button>
        </div>
        <div class="row">
          <button class="login_btn btn" @click="submitFn">登录</button>
        </div>
      </section>
      <!-- 微信扫码登录 -->
      <section id="weixin" v-show="!isShowLoginType" class="QrLogin">
        微信扫码登录
      </section>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import {
  getValidationCode,
  LoginReginAPI,
  PhoneBindingAPI,
} from "../request/api";
import { verifyMobilePhoneNumber } from "../utils";

export default {
  data() {
    return {
      isShowLoginType: true,
      //手机号
      phoneNumber: "",
      //验证码信息
      msg: "向右滑动",
      //获取验证码按钮的状态
      getCodeStatus: true,
      //获取验证码间隔秒数
      count: 6,
      //验证码
      Code: "",
    };
  },
  methods: {
    ...mapActions({
      asyncChangeToastShow: "toastShow/asyncChangeToastShow",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    //手机号，滑动验证函数
    validationCode() {
      if (!verifyMobilePhoneNumber(this.phoneNumber)) {
        //调用自定义弹窗
        this.asyncChangeToastShow({
          toastType: "danger",
          toastMsg: "请输入正确的手机号",
        });
        return false;
      }
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        //调用自定义弹窗
        this.asyncChangeToastShow({
          toastType: "danger",
          toastMsg: "请完成滑动验证",
        });
        return false;
      }
      return true;
    },
    //修改获取验证码按钮样式
    modifyButtonStyles() {
      this.getCodeStatus = false;
      let timer = setInterval(() => {
        if (this.count <= 0) {
          clearInterval(timer);
          this.count = 6;
          this.getCodeStatus = true;
        }
        this.count--;
      }, 1000);
    },
    async getCode() {
      //验证手机号和滑动验证码
      if (!this.validationCode()) return;
      //发送获取验证码请求
      let res = await getValidationCode({ phone: this.phoneNumber.trim() });
      //终止逻辑 提高代码可读性
      if (!res) return;
      if (res.code == 0) {
        //调用自定义弹窗
        this.asyncChangeToastShow({
          toastType: "success",
          toastMsg: "验证发已发送",
        });
        //限制频繁获取验证码
        this.modifyButtonStyles();
      }
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //登录按钮函数(发送登录请求)
    async submitFn() {
      //验证手机号和滑动验证码
      if (!this.validationCode()) return;
      if (!this.Code.trim()) {
        //调用自定义弹窗
        this.asyncChangeToastShow({
          toastType: "danger",
          toastMsg: "请输入验证码",
        });
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //如果有uuid说明是首次登录发送绑定手机号请求
        res = await PhoneBindingAPI({
          verifyCode: this.Code.trim(),
          phone: this.phoneNumber.trim(),
          uuid,
        });
      } else {
        //否则发送普通登录请求
        res = await LoginReginAPI({
          verifyCode: this.Code.trim(),
          phone: this.phoneNumber.trim(),
        });
      }

      if (!res) return;

      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      //切换登录状态
      this.changeLoginStatus(true);
      //切换模态状态
      this.changeIsShowLogin(false);
      // 清除地址栏中的code
      this.$router.push(this.$route.path);
      // 删除uuid
      localStorage.removeItem("uuid");
      // 获取用户信息
      this.asyncChangeUserInfo();
      //调用自定义弹窗
      this.asyncChangeToastShow({
        toastType: "success",
        toastMsg: "欢迎宝贝",
      });
    },
    //加载微信扫码登录验证码
    showQrCode() {
      //切换登录窗口内容，显示微信登陆二维码
      this.isShowLoginType = false;
      //加载二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggcXJjb2RlIHsNCiAgbWFyZ2luLXRvcDogMjBweDsNCn0NCg==",
      });
    },
    //vuex中登录框显示状态
    ...mapMutations({
      changeIsShowLogin: "isShowLogin/changeIsShowLogin",
      changeLoginStatus: "loginStatus/changeLoginStatus",
    }),
  },
  computed: {},
};
</script>

<style lang="less" scoped>
.loginmodal {
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  position: fixed;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    width: 555px;
    height: 423px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    background: url("../assets/img/login-box-bg.png");
    .close {
      cursor: pointer;
      position: absolute;
      right: 50px;
      top: 10px;
    }
    .switchOn {
      cursor: pointer;
      margin-top: 20px;
      display: flex;
      justify-content: center;
      font-size: 20px;
      div {
        margin: 0 10px;
        color: #9a9bb3;
        &.active {
          color: #030303;
        }
      }
    }
    .phoneLogin {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;

      .row {
        display: flex;
        margin-bottom: 20px;

        .btn {
          cursor: pointer;
          height: 50px;
          border: none;
        }
        .btncode {
          margin-left: 4px;
        }
        .login_btn {
          font-size: 20px;
          color: white;
          background-color: #0a328e;
          width: 100%;
        }
        .ipt {
          outline: none;
          box-sizing: border-box;
          border: 1px solid #999;
          height: 50px;
          flex: 1;
        }
      }
    }
    //登录二维码居中
    .QrLogin {
      display: flex;
      justify-content: center;
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
